﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="QueryResultWriter.cs" company="Jared Schlicht">
//   Copyright (c) 2011 Jared Schlicht.
// </copyright>
// <summary>
//   Writes query results to the specified text writer in CSV form.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace JSchlicht.SqlCsv
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    using CsvHelper;

    /// <summary>
    /// Writes query results to the specified text writer in CSV form.
    /// </summary>
    public class QueryResultWriter : IDisposable
    {
        #region Constants and Fields

        /// <summary>
        /// Used to write CSV data. This object is part of the CsvHelper library.
        /// </summary>
        private readonly CsvWriter csvWriter;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="QueryResultWriter"/> class.
        /// </summary>
        /// <param name="textWriter">
        /// The text writer to output the CSV data to.
        /// </param>
        public QueryResultWriter(TextWriter textWriter)
        {
            this.csvWriter = new CsvWriter(textWriter);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.csvWriter.Dispose();
        }

        /// <summary>
        /// Writes the specified records to the current text writer.
        /// </summary>
        /// <param name="records">The records to output in CSV form.</param>
        public void Write(IEnumerable<string[]> records)
        {
            foreach (string[] record in records)
            {
                foreach (string cell in record)
                {
                    this.csvWriter.WriteField(cell);
                }

                this.csvWriter.NextRecord();
            }

            // Add an extra line at the end, in case multiple sql query results should be written.
            this.csvWriter.NextRecord();
        }

        #endregion
    }
}